//
//  HCConsoleVcr.m
//  HCToolBox
//
//  Created by Hotacool on 2019/3/19.
//

#import "HCConsoleVcr.h"
#import "UIView+HCTB.h"
#import "NSObject+HCTB.h"
#import "HCConsoleView.h"
//#import "IQKeyboardManager.h"

static const CGFloat kMenuWidth = 44;
static const CGFloat kActionReactWidth = 40.0;
static const CGFloat kConsoleHeight = 440.0;
@interface HCConsoleVcr ()
@property (nonatomic, strong) UIButton *menuButton;
@property (nonatomic, strong) HCConsoleView *consoleView;
@end

@implementation HCConsoleVcr {
    UIPanGestureRecognizer *_pan;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    @weakIt(self);
    self.view.hctb_hitTestBlock = ^__kindof UIView * _Nonnull(CGPoint point, UIEvent * _Nonnull event, __kindof UIView * _Nonnull originalView) {
        @strongIt(self);
        if (originalView == self.view) {
            return nil;
        }
        return originalView;
    };
    [self.menuButton addTarget:self action:@selector(menuButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    _pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(doPan:)];
    [self.menuButton addGestureRecognizer:_pan];
    [self.view addSubview:self.menuButton];
    self.menuButton.hctb_hitTestBlock = ^__kindof UIView * _Nonnull(CGPoint point, UIEvent * _Nonnull event, __kindof UIView * _Nonnull originalView) {
        return originalView;
    };
    
    self.consoleView.frame = CGRectMake(0, self.view.bounds.size.height - kConsoleHeight, self.view.bounds.size.width, kConsoleHeight);
    [self.view insertSubview:self.consoleView belowSubview:self.menuButton];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
}

- (UIButton *)menuButton {
    if (!_menuButton) {
        _menuButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.bounds.size.width-kMenuWidth, self.view.bounds.size.height/2.0-kMenuWidth/2.0, kMenuWidth, kMenuWidth)];
        _menuButton.backgroundColor = hcRGB_HEX(0xEC2E31);
        _menuButton.layer.cornerRadius = CGRectGetHeight(_menuButton.bounds) / 2;
        _menuButton.clipsToBounds = YES;
        [_menuButton setTitle:@"Log" forState:UIControlStateNormal];
        [_menuButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _menuButton.titleLabel.adjustsFontSizeToFitWidth = YES;
        _menuButton.titleLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
    }
    return _menuButton;
}

- (HCConsoleView *)consoleView {
    if (!_consoleView) {
        _consoleView = [[HCConsoleView alloc] init];
        _consoleView.hidden = YES;
        _consoleView.backgroundColor = [UIColor blackColor];
    }
    return _consoleView;
}

- (void)menuButtonClick:(UIButton*)sender {
    NSString *menuCenterKey = @"menuCenter";
    if (self.consoleView.hidden) {
        _pan.enabled = NO;
        self.consoleView.hidden = NO;
        [self.menuButton hctb_setObject:[NSValue valueWithCGPoint:self.menuButton.center] forKey:menuCenterKey];
        self.menuButton.center = CGPointMake(CGRectGetMaxX(self.consoleView.frame) - self.menuButton.width/2, CGRectGetMinY(self.consoleView.frame) - self.menuButton.height/2);
    } else {
        _pan.enabled = YES;
        self.consoleView.hidden = YES;
        [self.consoleView endEditing:YES];
        self.menuButton.center = [[self.menuButton hctb_objectForKey:menuCenterKey] CGPointValue];
        [self.menuButton hctb_setObject:nil forKey:menuCenterKey];
    }
    [self showConsoleView:!self.consoleView.hidden];
}

- (void)showConsoleView:(BOOL)isShow
{
//    [IQKeyboardManager sharedManager].enable = !isShow;
}

- (void)doPan:(UIPanGestureRecognizer*)p {
    CGPoint panPoint = [p locationInView:self.view];
    if(p.state == UIGestureRecognizerStateBegan) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(changeStatus) object:nil];
    }
    if(p.state == UIGestureRecognizerStateChanged) {
        self.menuButton.center = CGPointMake(panPoint.x, panPoint.y);
    } else if(p.state == UIGestureRecognizerStateEnded) {
        [self performSelector:@selector(changeStatus) withObject:nil afterDelay:3.0];
        
        if(panPoint.x <= hcScreenBoundsWidth/2) {
            if(panPoint.y <= kActionReactWidth+kMenuWidth/2 && panPoint.x >= kActionReactWidth+kMenuWidth/2) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.menuButton.center = CGPointMake(panPoint.x, kMenuWidth/2);
                }];
            } else if(panPoint.y >= hcScreenBoundsHeight-kMenuWidth/2-kActionReactWidth && panPoint.x >= kActionReactWidth+kMenuWidth/2) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.menuButton.center = CGPointMake(panPoint.x, hcScreenBoundsHeight-kMenuWidth/2);
                }];
            } else if (panPoint.x < kMenuWidth/2+kActionReactWidth && panPoint.y > hcScreenBoundsHeight-kMenuWidth/2) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.menuButton.center = CGPointMake(kMenuWidth/2, hcScreenBoundsHeight-kMenuWidth/2);
                }];
            } else {
                CGFloat pointy = panPoint.y < kMenuWidth/2 ? kMenuWidth/2 :panPoint.y;
                [UIView animateWithDuration:0.3 animations:^{
                    self.menuButton.center = CGPointMake(kMenuWidth/2, pointy);
                }];
            }
        } else if(panPoint.x > hcScreenBoundsWidth/2) {
            if(panPoint.y <= kActionReactWidth+kMenuWidth/2 && panPoint.x < hcScreenBoundsWidth-kMenuWidth/2-kActionReactWidth ){
                [UIView animateWithDuration:0.3 animations:^{
                    self.menuButton.center = CGPointMake(panPoint.x, kMenuWidth/2);
                }];
            } else if(panPoint.y >= hcScreenBoundsHeight-kActionReactWidth-kMenuWidth/2 && panPoint.x < hcScreenBoundsWidth-kMenuWidth/2-kActionReactWidth) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.menuButton.center = CGPointMake(panPoint.x, hcScreenBoundsHeight-kMenuWidth/2);
                }];
            } else if (panPoint.x > hcScreenBoundsWidth-kMenuWidth/2-kActionReactWidth && panPoint.y < kMenuWidth/2) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.menuButton.center = CGPointMake(hcScreenBoundsWidth-kMenuWidth/2, kMenuWidth/2);
                }];
            } else {
                CGFloat pointy = panPoint.y > hcScreenBoundsHeight-kMenuWidth/2 ? hcScreenBoundsHeight-kMenuWidth/2 :panPoint.y;
                [UIView animateWithDuration:0.3 animations:^{
                    self.menuButton.center = CGPointMake(hcScreenBoundsWidth-kMenuWidth/2, pointy);
                }];
            }
        }
    }
}

- (void)changeStatus {
    [UIView animateWithDuration:0.5 animations:^{
        UIEdgeInsets insets = hcViewSafeAreInsets(self.view);//TODO: safearea fix
        CGFloat x = self.menuButton.center.x < kActionReactWidth+kMenuWidth/2 ? insets.left :  self.menuButton.center.x > hcScreenBoundsWidth - kActionReactWidth -kMenuWidth/2 ? hcScreenBoundsWidth : self.menuButton.center.x;
        CGFloat y = self.menuButton.center.y < kActionReactWidth + kMenuWidth/2 ? insets.top : self.menuButton.center.y > hcScreenBoundsHeight - kActionReactWidth - kMenuWidth/2 ? hcScreenBoundsHeight : self.menuButton.center.y;
        self.menuButton.center = CGPointMake(x, y);
    }];
}

- (BOOL)searchFieldIsFirstResponse{
    return [self.consoleView.searchTextField isFirstResponder];
}

#pragma mark - keyboard
- (void)keyboardWillShowNotification:(NSNotification *)notification {
    if ([self.consoleView.searchTextField isFirstResponder]) {
        CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        self.consoleView.frame = CGRectMake(0, self.view.bounds.size.height - kConsoleHeight - rect.size.height, self.view.bounds.size.width, kConsoleHeight);
        self.statusChangeBlock ? self.statusChangeBlock(YES) : nil;
    }
}

- (void)keyboardWillHideNotification:(NSNotification *)notification {
    if ([self.consoleView.searchTextField isFirstResponder])
    {
        self.consoleView.frame = CGRectMake(0, self.view.bounds.size.height - kConsoleHeight, self.view.bounds.size.width, kConsoleHeight);
        self.statusChangeBlock ? self.statusChangeBlock(NO) : nil;
    }
}
@end
